package com.weilele.mvvmlib.sample.fg


import android.os.Bundle
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.PagerSnapHelper
import com.weilele.base.library.BaseFragment
import com.weilele.mvvm.base.helper.LiveDataWrap
import com.weilele.mvvm.base.helper.annotation.MvvmViewModel
import com.weilele.mvvm.base.helper.appCompatActivity
import com.weilele.mvvm.base.helper.data
import com.weilele.mvvm.base.helper.wrapOnlySuccessObserver
import com.weilele.mvvm.utils.android_r.fullScreen
import com.weilele.mvvm.utils.vLaout.MvvmMutableTypeListAdapter
import com.weilele.mvvm.utils.vLaout.mvvmMutableTypeAdapter
import com.weilele.mvvmlib.databinding.FragmentBlankBinding
import com.weilele.mvvmlib.sample.HomeHolder

class BlankFragment : BaseFragment<FragmentBlankBinding>() {
    //    private val adapter = mvvmMutableTypeAdapter(
//        MeiziHolder::class.java, HomeHolder::class.java
//    )
    private val adapter = MvvmMutableTypeListAdapter<Any>(
        object : DiffUtil.ItemCallback<Any>() {
            override fun areItemsTheSame(oldItem: Any, newItem: Any): Boolean {
                return this@BlankFragment.areItemTheSame(oldItem, newItem)
            }

            override fun areContentsTheSame(oldItem: Any, newItem: Any): Boolean {
                return this@BlankFragment.areItemTheSame(oldItem, newItem)
            }

        }, MeiziHolder::class.java, HomeHolder::class.java
    )

    override fun initUi(savedInstanceState: Bundle?) {
        super.initUi(savedInstanceState)
        appCompatActivity.fullScreen(true)
        mBinding.rcv.adapter = adapter
        mBinding.rcv.setHasFixedSize(true)
        PagerSnapHelper().attachToRecyclerView(mBinding.rcv)
    }

    override fun initData() {
        super.initData()
        viewModel.getPic(true)
    }


    private val initOnListScrollEndListener by lazy {
        viewModel.pageData.data?.setOnListScrollEndListener(adapter) {
            viewModel.getPic(false)
        }
    }

    @MvvmViewModel
    private lateinit var viewModel: MeiziViewModel

    override fun getObserverLiveData(): List<LiveDataWrap>? {
        return listOf(
            viewModel.pageData wrapOnlySuccessObserver {
                initOnListScrollEndListener
                it.refreshAdapter(
                    adapter,
                    appendData = if (it.hasNextPage)
                        Pair("正在加载...", null)
                    else
                        Pair("数据已经加载完成", null),
                    isAddAllAppendData = false,
//                    areItemTheSame = ::areItemTheSame,
//                    areContentsTheSame = ::areItemTheSame,
                )
            }
        )
    }

    private fun areItemTheSame(old: Any?, new: Any?): Boolean {
        return old == new
    }
}